﻿package Cain.Bit
{
	import flash.display.DisplayObject;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.utils.getDefinitionByName;
	import com.greensock.TweenLite;
	/**
	 * 布朗隨機動態粒子v1.01 2010.9.23
	 * @author Cain@2009 in ADCAST
	 */
	public class Bit extends Sprite
	{
		private var bt:Class;
		private var ax:Number;
		private var ay:Number;
		private var vx:Number;
		private var vy:Number;
		private var max_ax:Number;
		private var max_ay:Number;
		private var live:int;
		private var g:Number;
		private var wind:Number;
		/**
		 * 顯視物件
		 */
		public var bt_mc:DisplayObject;
		/**
		 * 粒子初始化
		 * @param	_bt 元件中套用動態的Class 物件名
		 * @param	_max_ax x加速度極限 
		 * @param	_max_ay y加速度極限
		 * @param	_live 壽命
		 * @param	_g 重力
		 * @param	_wind 風向
		 */
		public function Bit(_bt:String, _max_ax:Number = 1, _max_ay:Number = 1, _live:int = 150, _g:Number = 0, _wind:Number=0) 
		{
			bt = getDefinitionByName(_bt) as Class;
			live = _live;
			max_ax = _max_ax;
			max_ay = _max_ay;
			g = _g;
			wind = _wind;
			init();
		}
		/**
		 * 增加x加速
		 */
		public function set _vx(_x:Number):void 
		{
			vx += _x;
		}
		/**
		 * 增加y加速
		 */
		public function set _vy(_y:Number):void 
		{
			vy += _y;
		}
		/**
		 * 增加風力向量
		 */
		public function set _wind(_x:Number):void 
		{
			wind += _x;
		}
		/**
		 * 增加重力向量
		 */
		public function set _g(_y:Number):void 
		{
			g += _y;
		}
		/**
		 * 移除自己
		 * @param	now 淡出時間
		 */
		public function remove(now:Number=0):void
		{
			if (now<=0) 
			{
				end();
			}else 
			{
				TweenLite.to(this, now, { alpha:0, onComplete:end } );
			}
			
		}
		private function end():void 
		{
			Sprite(parent).removeChild(this);
		}
		private function init():void
		{
			bt_mc = new bt();
			addChild(bt_mc);
			cacheAsBitmap = true;
			play();
		}
		
		private function play():void
		{
			vx = 0;
			vy = 0;
			addEventListener(Event.ENTER_FRAME, move);
			addEventListener(Event.REMOVED_FROM_STAGE, unload);
		}
		
		private function unload(e:Event=null):void 
		{
			removeEventListener(Event.ENTER_FRAME, move);
			removeEventListener(Event.REMOVED_FROM_STAGE, unload);
			bt = null;
			bt_mc = null;
		}
		
		private function move(e:Event):void 
		{	
			ax = Math.random() * max_ax - (max_ax / 2);
			ay = Math.random() * max_ay - (max_ay /2);
			ax += wind;
			ay += g;
			vx += ax;
			vy += ay;
			x += vx;
			y += vy;
			if (live==0) 
			{
				remove();
			}else {
				live--;
			}
		}
	}
	
}